package baidu.controller;

import baidu.pojo.IDCardDistinguish;
import baidu.pojo.form.IDCardDistinguishAddForm;
import baidu.service.IDCardDistinguishService;
import baidu.service.WxUserCfg;
import baidu.units.AES;
import baidu.units.BaiduIdCardUnits;
import com.google.common.collect.ImmutableMap;
import common.pojo.CommonResult;
import httpclient.HttpClientUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**开放接口
 * Created by asus on 2018/12/21.
 */
@Controller
@RequestMapping("/idCard")
public class IDCardDistinguishController
{
    @Autowired
    WxUserCfg wxUserCfg;
    @Autowired
    IDCardDistinguishService  service;
    @RequestMapping(value = "/",method = RequestMethod.POST)
    @ResponseBody
    public CommonResult IDCardDistinguish(
            @RequestParam(value = "imgUrl",required = false) String imgUrl,
            HttpServletRequest request,
            @RequestParam(value = "inputName",required = false) String inputName,
            @RequestParam(value = "inputIdCard",required = false) String inputIdCard
    ){
        IDCardDistinguishAddForm addForm = new IDCardDistinguishAddForm();
        if(StringUtils.isBlank(imgUrl)){
            return CommonResult.returnFailsWrapper("请传入imgUrl");
        }
        if(StringUtils.isBlank(inputName)){
            return CommonResult.returnFailsWrapper("请传入inputName");
        }
        if(StringUtils.isBlank(inputIdCard)){
            return CommonResult.returnFailsWrapper("请传入inputIdCard");
        }
        String sessionId = request.getHeader("sessionId");
        if (StringUtils.isBlank(sessionId)) {
            return new CommonResult(3, "请重新登录");
        }
        CommonResult result = HttpClientUtils.get(wxUserCfg.getWxUserInfo(), ImmutableMap.of("sessionId", sessionId));
        if (result.isNotSuccess()) {
            result.setCode(3);
            return result;
        }
        Map map =(LinkedHashMap)result.getData();
        String openId=map.get("openId").toString();
        URL url = null;
        InputStream is=null;
        try {
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            url = new URL(imgUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置请求方式为"GET"
            conn.setRequestMethod("GET");
            //超时响应时间为5秒
            byte[] by = new byte[1024];

            conn.setConnectTimeout(5 * 1000);
            //通过输入流获取图片数据
             is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            Base64.Encoder encoder = Base64.getEncoder();
            String encode = encoder.encodeToString(data.toByteArray());
            Map param =  BaiduIdCardUnits.retuenMap(encode);
            if (param.size() == 0) {
                return CommonResult.returnFailsWrapper("请上传身份证正面照片并确认图像清晰可见");
            }
            if (param.get("name") != null && param.get("name").equals(inputName)) {
            } else {
                return CommonResult.returnFailsWrapper("请上传本人身份证照片");
            }
            if (param.get("idCard") != null && param.get("idCard").equals(inputIdCard)) {
            } else {
                return CommonResult.returnFailsWrapper("请上传本人身份证照片");
            }

            addForm.setAddress(AES.encrypt(param.get("address").toString()));
            addForm.setOpenId(openId);
            addForm.setBirth(param.get("birth").toString());
            addForm.setCreateTime(new Date());
            addForm.setIdCard( AES.encrypt(param.get("idCard").toString()));
            addForm.setIdCardImg(imgUrl);
            addForm.setName( param.get("name").toString());
            addForm.setInputName( inputName);
            addForm.setInputIdCard( AES.encrypt(inputIdCard));
            addForm.setNation(param.get("nation").toString());
            addForm.setSex(param.get("sex").toString());
            int i= service.addIDCardDistinguish(addForm);
            if(i>0){
                return CommonResult.returnBoolWrapper(i>0,"验证失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.returnFailsWrapper("验证失败");
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //打开链接

        return CommonResult.returnFailsWrapper("验证失败");
    }


    @RequestMapping(value = "/exist",method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getUserInfo(
            HttpServletRequest request
    ){
        String sessionId = request.getHeader("sessionId");
        if (StringUtils.isBlank(sessionId)) {
            return new CommonResult(3, "请重新登录");
        }
        CommonResult result = HttpClientUtils.get(wxUserCfg.getWxUserInfo(), ImmutableMap.of("sessionId", sessionId));
        if (result.isNotSuccess()) {
            result.setCode(3);
            return result;
        }
        Map map =(LinkedHashMap)result.getData();
        String openId=map.get("openId").toString();
        boolean bool = service.getIDCardDistinguishNum(openId)>0;
        if (bool){
            return CommonResult.returnDataWrapper("true");
        }
        return CommonResult.returnDataWrapper("false");
    }

    @RequestMapping(value = "/judge/name",method = RequestMethod.POST)
    @ResponseBody
    public CommonResult getUserInfoName(
            @RequestParam(value = "realName",required = false) String realName,
            @RequestParam(value = "openId",required = false) String openId
    ) {
            if(StringUtils.isBlank(realName)){
                return CommonResult.returnFailsWrapper("请传入真实姓名");
            }
            if(StringUtils.isBlank(openId)){
                return CommonResult.returnFailsWrapper("请传入openId");
            }
        IDCardDistinguish distinguish = service.getIDCardDistinguishName(openId,realName);
        if(distinguish==null){
            return CommonResult.returnDataWrapper("false");
        }
        if(!distinguish.getName().equals(realName)){
            return CommonResult.returnDataWrapper("false");
        }
        return CommonResult.returnDataWrapper("true");
    }
}
